package com.leyou.item.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.pojo.Brand;
import com.leyou.pojo.Category;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 根据分页查询品牌
 * 以及动态排序
 * @author XiaoLuo
 * @ClassName: BrandServiceImpl
 * @Description: ${todo}
 * @date 2019/4/14 11:25
 */
@Service public class BrandServiceImpl implements BrandService {

	@Autowired private BrandMapper brandMapper;

	@Override public PageResult<Brand> queryBrandByPage(Integer page,
			Integer rows, String sortBy, Boolean desc, String key) {
		//开始分页   分页插件的方法
		PageHelper.startPage(page,rows);
		//过滤
		Example example = new Example(Brand.class);
		if(StringUtils.isNotBlank(key)){
			example.createCriteria().andLike("name","%"+key+"%")
					.orEqualTo("letter",key.toUpperCase());
		}
		//排序
		if(StringUtils.isNotBlank(sortBy)){
			String orderByClause = sortBy + (desc ? " DESC":" ASC");
			example.setOrderByClause(orderByClause);
		}
		//查询
		Page<Brand> brandPage = (Page<Brand>) brandMapper.selectByExample(example);
		return new PageResult<>(brandPage.getTotal(),brandPage);
	}

	/**
	 * 新增品牌
	 * @param brand
	 * @param cids
	 */

	@Override
	@Transactional
	public void saveBrand(Brand brand, List<Long> cids) {
		//新增品牌信息
		this.brandMapper.insertSelective(brand);
		//新增品牌和分类中间表
		for (Long cid : cids) {
			this.brandMapper.insertCategoryBrand(cid,brand.getId());
		}

	}

	/**
	 * 修改品牌管理
	 * @param brand
	 * @param cids
	 */
	@Override
	@Transactional
	public void updateBrand(Brand brand, List<Long> cids) {
		//品牌由于有ID，所以可以直接修改
		this.brandMapper.updateByPrimaryKeySelective(brand);
		//先删除之前品牌对应所有分类，然后重新添加

		this.brandMapper.deleteCategory(brand.getId());
		cids.forEach(cid->{
			this.brandMapper.insertCategoryBrand(cid,brand.getId());
		});

	}

	/**
	 * 根据bid删除品牌管理
	 * @param bid
	 */
	@Override public void deleteBrand(Long bid) {
			this.brandMapper.deleteBrand(bid);
			this.brandMapper.deleteCategory(bid);
	}

	/**
	 * 查询品牌名称
	 * @param brandId
	 * @return
	 */
	@Override public Brand queryBrandById(Long brandId) {

	return this.brandMapper.selectByPrimaryKey(brandId);
	}

	/**
	 * 根据分类动态查询品牌
	 * @param cid
	 * @return
	 */
	@Override public List<Brand> queryBrandByCategory(Long cid) {
		return this.brandMapper.queryByCategoryId(cid);

	}

}
